package com.ktjiaoyu.t382.controller;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.context.WebApplicationContext;

@Controller
@Scope("prototype")
public class ScopeController {
    private int count = 0;
    // 注入 WebApplicationContext 可以获得容器
    @Autowired
    private WebApplicationContext context;

    @GetMapping("/scope")
    public String testScope(HttpSession session) {
        printBeanInfo("scope", session);
        // 转发到/forward 控制器再打印一次
        return "forward:/forward";
    }

    @GetMapping("/forward")
    public String forward(HttpSession session) {
        printBeanInfo("forward", session);
        return null;
    }

    private void printBeanInfo(String type, HttpSession session) {
        System.out.println(type + "===================sessionId = " + session.getId());
        // 通过容器获得四种作用域的 role 对象并打印信息
        Object roleSingleton = context.getBean("roleSingleton");
        System.out.println(type + "-roleSingleton : " + roleSingleton);
        Object rolePrototype = context.getBean("rolePrototype");
        System.out.println(type + "-rolePrototype : " + rolePrototype);
        Object roleRequest = context.getBean("roleRequest");
        System.out.println(type + "-roleRequest : " + roleRequest);
        Object roleSession = context.getBean("roleSession");
        System.out.println(type + "-roleSession : " + roleSession);
    }
    
    @GetMapping("/count")
    public String count() {
        // 获取当前类型上标注的 Scope 注解的值
        String scope = this.getClass().getAnnotation(Scope.class).value();
        System.out.println(scope + "-count = " + ++count);
        return null;
    }
}
